$(document).ready(function() {
	/* Global variables for math operations*/
	var first_op = -1;
	var second_op = -1;
	var op_type = 0;

	/* Bind event for number buttons */
	$("#numbers button").bind('click', function (event) {
		var current = $(this).html();
		var prev = $("#result input[name='numbers']").val();
		$("#result input[name='numbers']").val( prev + current);
	});

	/* Bind event for operation buttons */
	$("#operations button").bind('click', function (event) {
		first_op = $("#result input[name='numbers']").val(); 
		$("#result input[name='numbers']").val("");
		
		switch ( $(this).html() ) {
			case '+':
				op_type = 'add';
				break;

			case '-':
				op_type = 'sup';
				break;

			case '/':
				op_type = 'div';
				break;

			case '*':
				op_type = 'mul';
				break;
		}
	});

	/* For IE and trueBrowsers */
	function getXmlHttp() {
		var xmlhttp;
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(E) {
				xmlhttp = false;
			}
		} 

		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
			xmlhttp = new XMLHttpRequest();
		}

		return xmlhttp;
	}

	/* Send our request and get response */
	function send(xmlhttp) {
		var url = 'req.php?fop=' + first_op + '&sop='
			+ second_op + '&type=' + op_type;

		xmlhttp.open('GET', url, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					/*var tmp = xmlhttp.responseText;*/
					/*alert(xmlhttp.responseText);*/
					$("#result input[name='numbers']").val( xmlhttp.responseText );
					//alert(xmlhttp.responseText);
					//alert(xmlhttp.responseText);
				}
			}
		};		
		xmlhttp.send(null);
	}

	/* Get result */
	$("#equal button").bind('click', function() {
		second_op = $("#result input[name='numbers']").val();
		$("#result input[name='numbers']").val("Опрацювання...");
		var request = getXmlHttp();
		send(request);
	});
});



